package com.example.main;

import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main02 {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2,
                2, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100),
                new ThreadPoolExecutor.CallerRunsPolicy());

        String msg="end";
        for (int i = 0; i < 10; i++) {
            executor.execute(new Task(msg+i,executor,i));
        }

        executor.execute(new Task(msg,executor,0));
        System.out.println("执行关闭线程池开始");
        executor.shutdown();
        System.out.println("执行关闭线程池结束");
        while (!executor.isTerminated()){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务正在执行中");
//            Thread.yield();
        }
        System.out.println("任务全部执行结束");
    }

    public static class Task implements Runnable{

        private final int i;
        private final String msg;
        private final ThreadPoolExecutor executor;

        public Task(String msg,ThreadPoolExecutor executor,int i) {
            this.msg = msg;
            this.executor=executor;
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(msg+" ===== "+Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(3+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("判断是否结束:"+msg);
//            if (Objects.equals(msg,"end")){
//                System.out.println("所有任务执行结束，准备关闭线程池");
//                executor.shutdown();
//                System.out.println("所有任务执行结束，关闭线程池完成");
//            }
        }
    }
}
